package com.wuxinwudai.android.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import android.util.Log;

/**
 * StreamUtil 工具类用于流操作
 * @author 吾心无待 于 2016年04月14日
 *
 */
public class StreamUtils {
	/**
	 * 从一个流中读取数据并保存为字节数组
	 * @param in 要读取的流
	 * @return 读取的字节数组
	 * @throws Exception
	 */
	public static byte[] toBytes(InputStream in) throws Exception{
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer= new byte[1024];
		int len = -1;
		while((len = in.read(buffer))!=-1){
			outputStream.write(buffer,0,len);
		}
		outputStream.close();
		in.close();
		return outputStream.toByteArray();
	}

	/**
	 * 从一个流中读取并数据并保存为字符串
	 * @param in 要读取的流
	 * @return
	 */
	public static String toString(InputStream in) throws Exception{
		BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"), 512 * 1024);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line);
		}
		in.close();
		return sb.toString();
	}
}
